package com.teen9g.infoplatformserver.interceptor;

import com.teen9g.context.BaseContext;
import com.teen9g.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author teen9g
 * 登录拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        if (request.getMethod().equals(HttpMethod.OPTIONS.toString())) {
            return true;
        }

        //从请求头中获取token
        String token = request.getHeader("Authorization");
        log.info("token:{}", token);
        try {
            Claims claims = JwtUtil.parseToken(token);
            log.info("token解析成功，Claims: {}", claims);
            BaseContext.setCurrentUser(claims.get("username", String.class));
            BaseContext.setCurrentUserId(claims.get("id", Integer.class));
            return true;
        } catch (Exception e) {
            // token解析失败
            log.error("token解析失败", e);
            response.setStatus(401);
            return false;
        }
    }
}
